package com.tz.util;

import com.tz.util.qiniuUtils.QiniuParamter;
import com.tz.util.qiniuUtils.QiniuUtil;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.UUID;

/**
 *
 * 本地项目工具类
 *
 */
public class StringHelper {


    /**
     * 获得当前的时间转成 字符串 2015-05-12 这种格式 为了保存资讯图片概要路径用
     */
    public static String getStringByNow() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(new Date());
    }

    /**
     * 上传概要图片的公共方法
     * @param request
     * @param filePath
     * @return
     * @throws java.io.IOException
     */
    public static String upload(HttpServletRequest request, String filePath) throws IOException {
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        if (multipartResolver.isMultipart(request)) {
            String path = null;

            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            Iterator<String> iter = multiRequest.getFileNames();
            while (iter.hasNext()) {
                MultipartFile file = multiRequest.getFile((String) iter.next());
                if (file != null && file.getSize() > 0) {
                    File folder = new File(filePath);
                    // File folder = new File(filePath + "/" + StringHelper.getStringByNow());
                    if (!folder.exists()) {
                        folder.mkdirs();
                    }
                    String fileName = file.getOriginalFilename();
                    //防止出现中文乱码
                    fileName=new String(fileName.getBytes(),"UTF-8");
                    SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
                    String newFileName =  df.format(new Date()) + "_" +  fileName;
                    path = filePath + "/"  + newFileName;
                    File localFile = new File(path);
                    file.transferTo(localFile);
                    return path;
                } else {
                    return null;
                }
            }
        }
        return null;
    }

    /**
     * 上传概要图片的公共方法
     * @param request
     * @param filePath
     * @return
     * @throws java.io.IOException
     */
    public static String[] doupload(HttpServletRequest request, String filePath ,int size) throws IOException {
        String[] urls = new String[size];
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        if (multipartResolver.isMultipart(request)) {
            String path = null;

            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            Iterator<String> iter = multiRequest.getFileNames();
            int index = 0;
            while (iter.hasNext()) {
                MultipartFile file = multiRequest.getFile((String) iter.next());
                if (file != null && file.getSize() > 0) {
                    File folder = new File(filePath);
                   // File folder = new File(filePath + "/" + StringHelper.getStringByNow());
                    if (!folder.exists()) {
                        folder.mkdirs();
                    }
                    String fileName = file.getOriginalFilename();
                    //防止出现中文乱码
                    fileName=new String(fileName.getBytes(),"UTF-8");
                    SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
                    String newFileName =  df.format(new Date()) + "_" +  fileName;
                    path = filePath + "/"  + newFileName;
                    File localFile = new File(path);
                    file.transferTo(localFile);
//                  return path;
                    urls[index] = path;
                    index ++;
                } else {
                    return null;
                }
            }
        }
        return urls;
    }


    /**
     * 上传商品图片到七牛 并 返回 七牛的外连
     * @param filePathurl  本地文件路径
     * @param categoryId    分类Id
     * @throws IOException
     */
    public  static  String uploadAndgetUrl(String key_suff ,String filePathurl ,Integer categoryId) throws IOException {
        System.out.println("filePathurl=="+filePathurl);
        //本地文件路径
        String path = filePathurl.replace("\"","");
        //拼接上传的key
        String goodKey = key_suff +  categoryId + "/"+path.substring(path.lastIndexOf("/")+1);
        //去七牛上传指定的文件并为其命名key
        QiniuUtil.upload(path , goodKey);
        //获得七牛图片外链
        String qiniuUrl = QiniuParamter.URL + goodKey;
        //删除本地文件
        TmFileUtil.delete(new File(path));
        return qiniuUrl;
    }

    public  static  String uploadAndgetUrl(String key_suff ,String filePathurl) throws IOException {
        System.out.println("filePathurl=="+filePathurl);
        //本地文件路径
        String path = filePathurl.replace("\"","");
        //拼接上传的key
        String key = key_suff + "/" + UUID.randomUUID().toString()+path.substring(path.lastIndexOf("/")+1);
        //去七牛上传指定的文件并为其命名key
        QiniuUtil.upload(path , key);
        //获得七牛图片外链
        String qiniuUrl = QiniuParamter.URL + key;
        //删除本地文件
        TmFileUtil.delete(new File(path));
        return qiniuUrl;
    }

    /**
     * 获取订单流水号  时间（到毫秒）+三位随机数
     *
     * @return
     */
    public static String getOrderNum() {
        try {
            Thread.sleep(1L);//处理并发问题 延迟1毫秒
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmsssss");
        String num = Integer.toString((int) ((999 - 100) * Math.random() + 100));//取得一个100-999的3位随机数字字符串
        String orderNum = format.format(date) + num;
        return orderNum;
    }
}
